package com.yuan.blog.controller.web;
import com.yuan.blog.core.utils.R;
import com.yuan.blog.entity.CommentEntity;
import com.yuan.blog.entity.UserEntity;
import com.yuan.blog.exception.JsonException;
import com.yuan.blog.service.ICommentService;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Controller
@RequestMapping("/CommentController")
public class CommentController{

    @Autowired
    private ICommentService commentService;


    @PostMapping("/add")
    @ResponseBody
    public R add(@RequestBody CommentEntity commentEntity, HttpServletRequest req) throws Exception {
        UserEntity loginUser = (UserEntity) req.getSession().getAttribute("loginUser");
        if (loginUser == null) {
//            return R.error("请先登录");
            throw new JsonException(100,"请先登录");
        }

        // 1.获取表单数据
//        Map<String, String[]> parameterMap = req.getParameterMap();

        // 2.准备实体类
//        CommentEntity commentEntity = new CommentEntity();

        // 3.把Map中的数据拷贝到实体类中
//        BeanUtils.populate(commentEntity, parameterMap);

        // 4.入库
        commentEntity.setUserId(loginUser.getId());
        commentService.save(commentEntity);

        // 5.重定向当前帖子下面
//        return BaseConstants.BASE_REDIRECT+":InvitationController/info/"+commentEntity.getEntityId();
        return R.ok();
    }
}
